package com.loren.demo18.servlet;

import com.loren.demo18.third.aes.WXBizMsgCrypt;
import com.loren.demo18.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebServlet(name = "emailCallbackServlet", urlPatterns = "/email/callback")
public class EmailCallbackServlet extends HttpServlet {

    private static final long serialVersionUID = 8476113658048390973L;

    private static final String CORP_ID = "xxx";

    private static final String TOKEN = "xxx";

    private static final String AES_KEY = "xxx";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(TOKEN, AES_KEY, CORP_ID);
            String msgSignature = request.getParameter("msg_signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("email GET callback, msgSignature = {}, timestamp = {}, nonce = {}, echostr = {}", msgSignature, timestamp, nonce, echostr);
            String sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
            response.getWriter().write(sEchoStr);
        } catch (Exception e) {
            log.info("verify url error", e);
            response.getWriter().write(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取消息体
        String content = IOUtils.read(request.getReader());
        log.info("email POST callback\r\n {}", content);
        log.info("callback results");

        // 获取回调参数
        String msgSignature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        log.info("msgSignature = {}, timestamp = {}, nonce = {}", msgSignature, timestamp, nonce);
    }
}
